package com.leetcode.algorithm.y22.m07.w4;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

class AuthenticationManager {

	private int timeToLive;
	private Map<String, Integer> map;

	public AuthenticationManager(int timeToLive) {
		this.timeToLive = timeToLive;
		map = new HashMap<>();
	}

	public void generate(String tokenId, int currentTime) {
		map.put(tokenId, currentTime + timeToLive);
	}

	public void renew(String tokenId, int currentTime) {
		if (map.containsKey(tokenId) && map.get(tokenId).intValue() > currentTime) {
			map.put(tokenId, currentTime + timeToLive);
		}
	}

	public int countUnexpiredTokens(int currentTime) {
		int cnt = 0;
		for (Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator(); iterator.hasNext();) {
			Map.Entry<String, Integer> entry = iterator.next();
			if (entry.getValue().intValue() > currentTime) {
				cnt++;
			} else {
				iterator.remove();
			}
		}
		return cnt;
	}
}